package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MallMember;
import com.rockcent.mall.lib.domain.enumclass.MallAuditCertifyInfoStatusType;
import com.rockcent.mall.lib.dto.MallDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.MallMemberRepository;
import com.rockcent.mall.lib.repository.MallRepository;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * Created by Marco on 16-11-21.
 * 平台基础信息
 */
@RestController
public class MallController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallController.class);

    @Autowired
    private UserHelper userHelper;

    @Autowired
    MallRepository mallRepository;

    @Autowired
    private MallMemberRepository mallMemberRepository;

    /**
     * @api {GET} /mall/member_info 平台会员状态
     * @apiGroup M MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {String=NOT_MEMBER("不是会员"), PROBATION_MEMBER("试用期会员"),MEMBER("会员"), AUDITING("开通审核中"), AUDIT_REFUSE("开通失败")} mallMember 是否是会员
     * @apiSuccess {String=ALL("全部"), UN_AUDIT("未认证"), AUDIT("审核中"), AUDIT_PASS("审核通过"), NOT_AUDIT("审核不通过")} auditCertifyInfo 资质审核状态
     * @apiSuccess {String} probationDay 试用期剩余天数
     * @apiSuccess {String} auditCertifyInfoRemark 审核意见
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "auditCertifyInfo": "UN_AUDIT",
     *     "auditCertifyInfoRemark": "审核一件",
     *     "mallMember": "PROBATION_MEMBER",
     *     "probationDay": 12
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_INFO, method = RequestMethod.GET)
    public JsonResult mallMemberInfo(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if(mall==null) {
                jsonResult.remind("平台记录不存在",log);
                return;
            }
            MallDto mallDto = new MallDto();
            if (mall.getAuditCertifyInfoStatus() != null) {
                mallDto.setAuditCertifyInfo(mall.getAuditCertifyInfoStatus().toString());
                mallDto.setAuditCertifyInfoRemark(mall.getAuditCertifyInfoRemark());
                if (MallAuditCertifyInfoStatusType.AUDIT_PASS == mall.getAuditCertifyInfoStatus()) {
                    MallMember mallMember = mallMemberRepository.findByMallIdAndIsDelete(mall.getId(), Whether.NO);
                    int surplusDay = DateUtils.compareDate(RDateUtils.date2String(DateUtils.getCurrentDate(), "yyyy-MM-dd"), RDateUtils.date2String(mallMember.getDateDisabled(), "yyyy-MM-dd"), 0);
                    mallDto.setProbationDay(surplusDay);
                    mallDto.setMallMember(mallMember.getStatus().toString());
                }
            }
            jsonResult.data = mallDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {GET} /mall/info 平台基础信息
     * @apiGroup M MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {String} name 平台名称
     * @apiSuccess {String} hostname 域名地址
     * @apiSuccess {String} backgroundPicture 平台背景图
     * @apiSuccess {String} logoBigPicture 平台大LOGO
     * @apiSuccess {String} logoSmallPicture 平台小LOGO
     * @apiSuccess {String} tag 平台标签
     * @apiSuccess {String} introduce 平台描述
     * @apiSuccess {String} keyword 平台关键词
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shareRate 分享返利比率
     * @apiSuccess {String} serviceEmail 客服邮箱
     * @apiSuccess {String} serviceTelephone 客服电话
     * @apiSuccess {String} onlineQq 在线QQ
     * @apiSuccess {String} customerPlatformDomain 自定义域名
     * @apiSuccess {String} customerClientDomain 自定义C端域名
     * @apiSuccess {String=NOT_MEMBER("不是会员"), PROBATION_MEMBER("试用期会员"),MEMBER("会员"), AUDITING("开通审核中"), AUDIT_REFUSE("开通失败")} mallMember 是否是会员
     * @apiSuccess {String=ALL("全部"), UN_AUDIT("未认证"), AUDIT("审核中"), AUDIT_PASS("审核通过"), NOT_AUDIT("审核不通过")} auditCertifyInfo 资质审核状态
     * @apiSuccess {String} probationDay 试用期剩余天数
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "dateCreated": "2016-05-05 17:44:33",
     *     "lastUpdated": "2016-11-22 11:20:09",
     *     "version": 103,
     *     "name": "四方街",
     *     "hostname": "beta.b.dev.rockcent.com",
     *     "customerPlatformDomain": "beta.b.dev.rockcent.com",
     *     "customerClientDomain": "beta.c.dev.rockcent.com",
     *     "userInfoId": 2,
     *     "serveRate": "2.5",
     *     "shareRate": "70",
     *     "companyName": "秋秋雨幕",
     *     "salesCode": "M@yQjZoabU",
     *     "mobileHostName": "beta.c.dev.rockcent.com",
     *     "prodAudit": false,
     *     "isLogisticsAccess": "YES",
     *     "backgroundPicture": "http://www.baidu.com/logo.png",
     *     "logoBigPicture": "http://www.baidu.com/bigPic.png",
     *     "logoSmallPicture": "http://www.baidu.com/smallPic.png",
     *     "tag": "rockcent",
     *     "introduce": "tettr",
     *     "keyword": "plat",
     *     "serviceEmail": "qq123@qq.com",
     *     "serviceTelephone": "84434532",
     *     "onlineQq": "888@qq.com",
     *     "auditCertifyInfo": "UN_AUDIT",
     *     "mallMember": "PROBATION_MEMBER",
     *     "probationDay": 12
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            jsonResult.data = mall;
        };
        return doing.go(request, log);
    }

    /**
     * @api {PUT} /mall/update 平台基础信息更新
     * @apiGroup M MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} name 平台名称
     * @apiParam {String} logoBigPicture 平台大LOGO
     * @apiParam {String} logoSmallPicture 平台小LOGO
     * @apiParam {String} tag 平台标签
     * @apiParam {String} introduce 平台描述
     * @apiParam {String} keyword 平台关键词
     * @apiParam {String} serveRate 服务费比率
     * @apiParam {String} shareRate 分享返利比率
     * @apiParam {String} serviceEmail 客服邮箱
     * @apiParam {String} serviceTelephone 客服电话
     * @apiParam {String} onlineQq 在线QQ
     *
     * @apiSuccess {String} success Y为成功
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":{
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_UPDATE, method = RequestMethod.PUT)
    public JsonResult update(@RequestBody MallDto mallDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if(mall==null) {
                jsonResult.remind("平台记录不存在",log);
                return;
            }
            String name = mallDto.getName();
            if(StringUtils.isBlank(name)) {
                jsonResult.remind("平台名称 不能为空",log);
                return;
            }
            String logoBigPic = mallDto.getLogoBigPicture();
            if(StringUtils.isBlank(logoBigPic)) {
                jsonResult.remind("平台LOGO16:9 不能为空",log);
                return;
            }
            String logoSmallPic = mallDto.getLogoSmallPicture();
            if(StringUtils.isBlank(logoSmallPic)) {
                jsonResult.remind("平台LOGO1:1 不能为空",log);
                return;
            }
            String tag =mallDto.getTag();
            if(StringUtils.isBlank(tag)) {
                jsonResult.remind("平台标签 不能为空",log);
                return;
            }
            String introduce = mallDto.getIntroduce();
            if(StringUtils.isBlank(introduce)) {
                jsonResult.remind("平台介绍 不能为空",log);
                return;
            }
            String keyword = mallDto.getKeyword();
            if(StringUtils.isBlank(keyword)) {
                jsonResult.remind("平台关键词 不能为空",log);
                return;
            }
//            String serviceRate = mallDto.getServeRate();
//            if(StringUtils.isBlank(serviceRate)) {
//                jsonResult.remind("平台服务费 不能为空",log);
//                return;
//            }
//            String shareRate = mallDto.getShareRate();
//            if(StringUtils.isBlank(shareRate)) {
//                jsonResult.remind("分享返利比率 不能为空",log);
//                return;
//            }
            String serviceEmail = mallDto.getServiceEmail();
            if(StringUtils.isBlank(serviceEmail)) {
                jsonResult.remind("客服邮箱 不能为空",log);
                return;
            }
            if(!isEmail(serviceEmail)) {
                jsonResult.remind("客服邮箱 格式不正确",log);
                return;
            }
            String serviceTelephone = mallDto.getServiceTelephone();
            if(StringUtils.isBlank(serviceTelephone)) {
                jsonResult.remind("客服电话 不能为空",log);
                return;
            }
            String onlineQq = mallDto.getOnlineQq();
            if(StringUtils.isBlank(onlineQq)) {
                jsonResult.remind("在线QQ 不能为空",log);
                return;
            }
            mall.setName(name);
            mall.setLogoBigPicture(logoBigPic);
            mall.setLogoSmallPicture(logoSmallPic);
            mall.setTag(tag);
            mall.setIntroduce(introduce);
            mall.setKeyword(keyword);
            mall.setServiceEmail(serviceEmail);
            mall.setServiceTelephone(serviceTelephone);
            mall.setOnlineQq(onlineQq);
            mallRepository.save(mall);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /mall/custom_host_update 平台自定义域名与背景图更新
     * @apiGroup M MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} hostName 域名地址
     * @apiParam {String} customerPlatformDomain 自定义域名
     * @apiParam {String} backgroundPicture 广告图
     * @apiParam {String} icpNumber ICP备案号
     *
     * @apiSuccess {String} success Y为成功
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":{
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_CUSTOM_HOST_UPDATE, method = RequestMethod.POST)
    public JsonResult customHostUpdate(@RequestBody MallDto mallDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if (mall == null) {
                jsonResult.remind("平台记录不存在",log);
                return;
            }
            boolean isPass = false;
            String host = "";
            String hostName = mallDto.getHostName();
            if(StringUtils.isNotEmpty(hostName)) {
                isPass = true;
                host = hostName;
            }
            String customerPlatformDomain = mallDto.getCustomerPlatformDomain();
            if(StringUtils.isNotEmpty(customerPlatformDomain)) {
                isPass = true;
                host = customerPlatformDomain;
            }
            if(!isPass) {
                jsonResult.remind("域名地址 不能为空",log);
                return;
            }
            if(StringUtils.isNotEmpty(customerPlatformDomain) && StringUtils.isNotEmpty(hostName)) {
                jsonResult.remind("二级与自定义域名 不能同时设置",log);
                return;
            }
            Mall mallHost = mallRepository.findByHostnameOrCustomerPlatformDomain(host);
            if(mallHost!=null) {
                if(mallHost.getId().longValue()!=mall.getId().longValue()) {
                    jsonResult.remind("域名地址 已存在",log);
                    return;
                }
            }
            String backgroundPic = mallDto.getBackgroundPicture();
            if(StringUtils.isBlank(backgroundPic)) {
                jsonResult.remind("广告图 不能为空",log);
                return;
            }
            if(StringUtils.isNotEmpty(hostName)) {
                mall.setHostname(hostName);
            }
            if(StringUtils.isNotEmpty(customerPlatformDomain)) {
                mall.setCustomerPlatformDomain(customerPlatformDomain);
                mall.setOpenCustomDomain(Whether.YES);

                //增加ICP备案号
                if(StringUtils.isNotEmpty(mallDto.getIcpNumber())) {
                    mall.setIcpNumber(mallDto.getIcpNumber());
                }
            }
            mall.setBackgroundPicture(backgroundPic);
            mallRepository.save(mall);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * 判断输入的字符串是否符合Email格式.
     * @param email
     *
     * @return 符合Email格式返回true，否则返回false
     */
    private boolean isEmail(String email) {
        if (email == null || email.length() < 1 || email.length() > 256) {
            return false;
        }
        Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        return pattern.matcher(email).matches();
    }
}
